package com.example.dql.diary;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dql.dqltools.DqlTools.DqlDialogSure;
import com.dql.dqltools.DqlTools.DqlDialogWheelYearMonthDay;
import com.example.dql.diary.Http.Api;
import com.example.dql.diary.Http.HttpRequest;
import com.example.dql.diary.Model.WhetherDTO;
import com.example.dql.diary.PictureSelection.SelectPicActivity;
import com.example.dql.diary.Suspending.SuspendingActivity;
import com.example.dql.diary.Suspending.TelePhoenActivity;
import com.example.dql.diary.Utils.DqlDialogLoading;
import com.example.dql.diary.activity.BaseActivity;
import com.example.dql.diary.activity.LoginActivity;
import com.example.dql.diary.activity.MyRecycleActivity;

import com.example.dql.diary.activity.ShareActivity;
import com.example.dql.diary.activity.ViewAnimatorActivity;
import com.example.dql.diary.activity.WebViewActivity;
import com.google.gson.Gson;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends BaseActivity {
	public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	@BindView(R.id.btn_goLogin)
	Button btnGoLogin;
	@BindView(R.id.btn_dateDialog)
	Button btnDateDialog;
	private Dialog bottomDialog;
	private EditText editText;
	private EditText et_phone;
	private String loc;//当地时间
	private String cond_txt;//实况天气状况代码
	private String wind_dir;//风向
	private String wind_sc;//风力
	private String vis;//能见度，默认单位：公里
	private String tmp;//温度
	private String hum;//相对湿度
	private HttpRequest httpRequest;
	private Context context;
	private Activity mActivity;
	private Api mApi;
	public final int REQUEST_WHAT_WHETHER = 111;
	private DqlDialogWheelYearMonthDay mDqlDialogWheelYearMonthDay;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 != -1) {
				switch (msg.what) {
					case REQUEST_WHAT_WHETHER:
						Log.e("onResponse", msg.obj.toString());
						Gson gson = new Gson();
						WhetherDTO whether = gson.fromJson(msg.obj.toString(), WhetherDTO.class);
						loc = whether.getHeWeather6().get(0).getUpdate().getLoc();
						cond_txt = whether.getHeWeather6().get(0).getNow().getCond_txt();
						wind_dir = whether.getHeWeather6().get(0).getNow().getWind_dir();
						wind_sc = whether.getHeWeather6().get(0).getNow().getWind_sc();
						vis = whether.getHeWeather6().get(0).getNow().getVis();
						tmp = whether.getHeWeather6().get(0).getNow().getTmp();
						hum = whether.getHeWeather6().get(0).getNow().getHum();
						break;
					default:
						break;
				}
			}
		}
	};

	@Override
	public int getLayoutId() {
		return R.layout.activity_main2;
	}

	@Override
	public Activity bindActivity() {
		return this;
	}

	@Override
	public void init() {
		mActivity = MainActivity.this;
		mApi = new Api(handler, this);
//        ImmersionBar.with(this).init();
		//设置转场动画
	   /* Slide slide = new Slide();
		slide.setSlideEdge(Gravity.BOTTOM);
        slide.setDuration(1000);*/
	/*	Transition transition = new Slide();
		transition.setDuration(1500);*/
//        getWindow().setEnterTransition(transition);
//        getWindow().setSharedElementEnterTransition(transition);
//        TransitionSet mtransitionset=new TransitionSet();//制定过度动画set
//        mtransitionset.setDuration(0);
//        getWindow().setExitTransition(mtransitionset);
//        getWindow().setSharedElementExitTransition(mtransitionset);

		Button button = (Button) findViewById(R.id.btn_sb);
		Button btn_lp = (Button) findViewById(R.id.btn_pic_look);
		Button but_buggy = (Button) findViewById(R.id.btn_buggy);
		Button btn_whether = (Button) findViewById(R.id.btn_whether);
		Button btn_rec = (Button) findViewById(R.id.btn_goRec);
		editText = (EditText) findViewById(R.id.et_msg);
		et_phone = (EditText) findViewById(R.id.et_phone);
		btn_lp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(MainActivity.this, SelectPicActivity.class));
			}
		});
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				mApi.getWhether(REQUEST_WHAT_WHETHER, "CN101210401", "f772b3595ed843ef9e309261397da3cf");

				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						postRebort();
					}
				}, 3000);//3秒后执行Runnable中的run方法

			}
		});
		but_buggy.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				CrashReport.testJavaCrash();
			}
		});
		btn_whether.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
//                getWhether();
				mApi.getWhether(REQUEST_WHAT_WHETHER, "CN101210401", "f772b3595ed843ef9e309261397da3cf");
			}
		});
		btn_rec.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(MainActivity.this, MyRecycleActivity.class));
			}
		});
	}

	private void getWhether() {
		String time = String.valueOf(System.currentTimeMillis() / 1000);
		String url = "https://free-api.heweather.com/s6/weather/now";
		OkHttpClient okHttpClient = new OkHttpClient();
		RequestBody body = new FormBody.Builder()
				.add("location", "CN101210401")
				.add("key", "f772b3595ed843ef9e309261397da3cf")
				.build();
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				.build();
		Call call = okHttpClient.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
//               Log.e("onResponse: ",response.body().string() );
				Gson gson = new Gson();
				WhetherDTO whether = gson.fromJson(response.body().string(), WhetherDTO.class);
				loc = whether.getHeWeather6().get(0).getUpdate().getLoc();
				cond_txt = whether.getHeWeather6().get(0).getNow().getCond_txt();
				wind_dir = whether.getHeWeather6().get(0).getNow().getWind_dir();
				wind_sc = whether.getHeWeather6().get(0).getNow().getWind_sc();
				vis = whether.getHeWeather6().get(0).getNow().getVis();
				tmp = whether.getHeWeather6().get(0).getNow().getTmp();
				hum = whether.getHeWeather6().get(0).getNow().getHum();
			}
		});

	}


	private void postRebort() {
		String recordurl = "https://oapi.dingtalk.com/robot/send?access_token=0c4d8b8fee5bb3af5ec4e083dd25db78b4aeabe8461c845797aaf58e3e1f938e";
		String msg = editText.getText().toString();
		String phone = et_phone.getText().toString();
		String json = "{\"msgtype\":\"markdown\",\n" +
				"\"markdown\": {\n" +
				"\"title\":\"宁波天气\",\n" +
				"\"text\":\"#### 宁波天气 \n" +
				"@13973394928\n" +
				"" + cond_txt + "," + tmp + "度,风向：" + wind_dir + ",风级：" + wind_sc + ",能见度:" + vis + "公里,相对湿度：" + hum + "%\n" +
				"![screenshot](http://www.91danji.com/attachments/201603/03/17/1vkbrm6xn.jpg)\n" +
				"###### " + loc + "发布 [天气](https://weather.html5.qq.com/index?action=getWeatherById&cityid=330212&ch=001401) \"},\n" +
				"\"at\":{\n" +
				"\"atMobiles\":[\"13973394928\"],\n" +
				"\"isAtAll\":false\n" +
				"}\n" +
				"}";
		String myJson = "{\"msgtype\":\"text\",\"text\":{\"content\":\"" + msg + "\"},\"at\":{\"atMobiles\":[\"" + phone + "\"],\"isAtAll\":false}}";
		OkHttpClient mOkHttpClient = new OkHttpClient();
		RequestBody body = RequestBody.create(JSON, json);
		Request request = new Request.Builder()
				.url(recordurl)
				.post(body)
				.build();
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String str = response.body().string();
				Log.i("wangshu", str);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});


	}


	@OnClick({R.id.btn_goLogin, R.id.btn_float, R.id.btn_phone, R.id.btn_dateDialog,R.id.btn_sureDialog,R.id.btn_webView,R.id.btn_loadingDialog,R.id.btn_viewAnimator,R.id.btn_share})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.btn_goLogin:
				Intent intent = new Intent(mActivity, LoginActivity.class);
				ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(mActivity, btnGoLogin, "login");
				ActivityCompat.startActivity(mActivity, intent, options.toBundle());
				break;
			case R.id.btn_float:
				startActivity(new Intent(MainActivity.this, SuspendingActivity.class));
				break;
			case R.id.btn_phone:
				startActivity(new Intent(MainActivity.this, TelePhoenActivity.class));
				break;
			case R.id.btn_dateDialog:
				if (mDqlDialogWheelYearMonthDay == null) {
					initWheelYearMonthDayDialog();
				}
				mDqlDialogWheelYearMonthDay.show();
				break;
			case R.id.btn_sureDialog:
				final DqlDialogSure dqlDialogSure = new DqlDialogSure(MainActivity.this);
				dqlDialogSure.getTitleView().setText("下载地址");
				dqlDialogSure.getContentView().setText("https://www.baidu.com");
				dqlDialogSure.getSureView().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dqlDialogSure.cancel();
					}
				});
				dqlDialogSure.show();
				break;
			case R.id.btn_webView:
				startActivity(new Intent(MainActivity.this, WebViewActivity.class));
				break;

			case R.id.btn_loadingDialog:
				DqlDialogLoading dqlDialogLoading = new DqlDialogLoading(MainActivity.this);
				dqlDialogLoading.show();
				break;

			case R.id.btn_viewAnimator:
				startActivity(new Intent(MainActivity.this, ViewAnimatorActivity.class));
				break;
			case R.id.btn_share:
				startActivity(new Intent(MainActivity.this, ShareActivity.class));
				break;
		}
	}


	private void initWheelYearMonthDayDialog() {
		// ------------------------------------------------------------------选择日期开始
		mDqlDialogWheelYearMonthDay = new DqlDialogWheelYearMonthDay(this, 1900, 2018);
		mDqlDialogWheelYearMonthDay.getSureView().setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						if (mDqlDialogWheelYearMonthDay.getCheckBoxDay().isChecked()) {
							btnDateDialog.setText(
									mDqlDialogWheelYearMonthDay.getSelectorYear() + "年"
											+ mDqlDialogWheelYearMonthDay.getSelectorMonth() + "月"
											+ mDqlDialogWheelYearMonthDay.getSelectorDay() + "日");
						} else {
							btnDateDialog.setText(
									mDqlDialogWheelYearMonthDay.getSelectorYear() + "年"
											+ mDqlDialogWheelYearMonthDay.getSelectorMonth() + "月");
						}
						mDqlDialogWheelYearMonthDay.cancel();
					}
				});
		mDqlDialogWheelYearMonthDay.getCancleView().setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDqlDialogWheelYearMonthDay.cancel();
					}
				});
		// ------------------------------------------------------------------选择日期结束
	}

}
